//
//  webViewController.m
//  ShopingAssistant
//
//  Created by zhangbaochuan on 2018/5/14.
//  Copyright © 2018年 zy. All rights reserved.
//

#import "NNbHtmlWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <AlipaySDK/AlipaySDK.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "WXApi.h"
#import <MJRefresh/MJRefresh.h>


@interface NNbHtmlWebViewController ()<UIWebViewDelegate, CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property (nonatomic, strong) JSContext *jsContext;
@property (strong,nonatomic) CLLocationManager* locationManager;
@property (assign, nonatomic) double jingdu;
@property (assign, nonatomic) double weidu;
@end

@implementation NNbHtmlWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = YES;
    NSURL *url = [NSURL URLWithString:@"http://61.160.221.97:8080/web"];
    //    NSURL *url = [[NSBundle mainBundle] URLForResource:@"recharge" withExtension:@"html"];
    //    NSURL *url = [[NSBundle mainBundle] URLForResource:@"zbc" withExtension:@"html"];
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:url]];
    //无缓存js方式
    //    [self.webView loadRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0]];
    self.webView.scrollView.bounces = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction:) name:@"InfoNotification" object:nil];
    
    //    self.webView.scrollView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refause)];
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
        
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self startLocation];
    });
}

-(void)refause{
    NSURL *url = [NSURL URLWithString:@"http://61.160.221.97:8080/web"];
    //    NSURL *url = [[NSBundle mainBundle] URLForResource:@"recharge" withExtension:@"html"];
    //    NSURL *url = [[NSBundle mainBundle] URLForResource:@"zbc" withExtension:@"html"];
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:url]];
}

//开始定位
-(void)startLocation{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 100.0f;
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] >8.0){
            [self.locationManager requestWhenInUseAuthorization];
        }
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
//            _locationManager.allowsBackgroundLocationUpdates =YES;
        }
        [self.locationManager startUpdatingLocation];
    }
    
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
            
        casekCLAuthorizationStatusNotDetermined:
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationManager requestWhenInUseAuthorization];
            }break;
        default:break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    
    
    CLLocation *newLocation = locations[0];
    
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    
    self.jingdu = oldCoordinate.longitude;
    self.weidu = oldCoordinate.latitude;
    NSString *str = [NSString stringWithFormat:@"getLatLng(%f,%f)", self.weidu, self.jingdu];
    if (self.jsContext) {
        [self.jsContext evaluateScript:str];
    }else{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.jsContext evaluateScript:str];
        });
    }
    
    
    [manager stopUpdatingLocation];
    
}
- (void)InfoNotificationAction:(NSNotification *)notification{
    
    NSLog(@"%@",notification.userInfo);
    if ([[notification.userInfo objectForKey:@"resultStatus"] integerValue] == 1) {
        [self.jsContext evaluateScript:@"paycallback(0)"];//成功
    }else if ([[notification.userInfo objectForKey:@"resultStatus"] integerValue] == 0){
        [self.jsContext evaluateScript:@"paycallback(1)"];//失败
    }
    NSLog(@"---接收到通知---");
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"url ==%@",webView.request.URL);
    //    JSContext *js = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //    if (self.jingdu > 0) {
    //        NSString *jsStr = [NSString stringWithFormat:@"javascript:getLatLng(\"%f\",\%f\)",self.jingdu,self.weidu];
    //        [js evaluateScript:jsStr];
    //    }
    
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSLog(@"%@",_jsContext);
    _jsContext[@"chongzhi()"] =^(id obj){
        ////这里通过block回调从而获得h5传来的数据
        /*block中捕获JSContexts
         我们知道block会默认强引用它所捕获的对象，如下代码所示，如果block中直接使用context也会造成循环引用，这使用我们最好采用[JSContext currentContext]来获取当前的JSContext:
         */
        
        NSArray *args = [JSContext currentArguments];
        for (id obj in args) {
            NSLog(@"zobjc==%@",obj);
        }
        NSLog(@"zobjc==%@",[JSContext currentArguments]);
        
    };
    __weak typeof(self) weakSelf = self;
    _jsContext[@"payIOS"] =^(id obj){
        ////这里通过block回调从而获得h5传来的json数据
        /*block中捕获JSContexts
         我们知道block会默认强引用它所捕获的对象，如下代码所示，如果block中直接使用context也会造成循环引用，这使用我们最好采用[JSContext currentContext]来获取当前的JSContext:
         */
        
        NSArray *args = [JSContext currentArguments];
        
        NSLog(@"payzobjc==%@",[JSContext currentArguments]);
        if (args.count > 1) {
            JSValue *jsv = args[1];
            NSString *str = [jsv toString];
            if ([str containsString:@"alipay"]) {
                [weakSelf payalipay:[args[0] toString]];
            }else if([str containsString:@"weixin"]){
                [weakSelf jumpToBizPay:[args[0] toString]];
            }
        }
    };
    if (self.jingdu > 0) {
        NSString *jsStr = [NSString stringWithFormat:@"getLatLng(%f,%f)",self.jingdu,self.weidu];
        [self.jsContext evaluateScript:jsStr];
    }
}


-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    //网页加载失败 调用此方法
    NSLog(@"error = %@", error);
}
-(void)payalipay:(NSString *)ordString{
    [[AlipaySDK defaultService] payOrder:ordString fromScheme:@"thekongtiao" callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
    
}

- (void)jumpToBizPay:(id)object {
    
    if (![WXApi isWXAppInstalled]) {
        return;
    }else if (![WXApi isWXAppSupportApi]){
        return ;
    }
    //============================================================
    // V3&V4支付流程实现
    // 注意:参数配置请查看服务器端Demo
    // 更新时间：2015年11月20日
    //============================================================
    
    
    
    id  JSONString = object;
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    if(dict != nil){
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        [WXApi sendReq:req];
        //日志输出
        //                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
        
    }
}

@end
